$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

$(document).ready(function () {
    var $jqGrid = $("#jqGrid");
    RFQ.jqGrid("#jqGrid").init({
        url: ctx+'/rfqQuotationLock/rfqQuotationLockList',
		postData:{rfqMethod:$("#rfqMethod").val()},
        colModel: [
				{
					label: '询单序号',
					name: 'id',
					index: 'id',
					width: 80,
					key: true,
					hidden:true
				},
                {
                    label: '供应商',
                    name: 'supplierId',
                    hidden:true
                },
				{
					label: '询价单号',
					name: 'unifiedRfqNum',
					index: 'UNIFIED_RFQ_NUM',
					align:'center',
					hidden:true,
					width: 80,
					formatter:selectFormatter
				},
            {
                label: '询价单号',
                name: 'ouRfqNum',
                index: 'OU_RFQ_NUM',
                align:'center',
                width: 80,
                formatter:selectFormatter
            },
				{
					label: '询单标题',
					name: 'title',
					index: 'TITLE',
					align:'center',
					width: 80
				},
				{
					label: '采购商',
					name: 'ouName',
					index: 'OU_NAME',
					align:'center',
					width: 80
				},
				{
					label: '发布人',
					name: 'issueUsername',
					index: 'ISSUE_USERNAME',
					align:'center',
					width: 60
				},
				{
					label: '报价开始时间',
					name: 'startDate',
					index: 'START_DATE',
					align:'center',
					width: 80
				},
				{
					label: '报价截止时间',
					name: 'quotationEndDate',
					index: 'QUOTATION_END_DATE',
					align:'center',
					width: 90
				},
				{
					label: '报价状态',
					name: 'status',
					index: 'TYPE',
					align:'center',
					width: 60,
					formatter:formatRfqQuotationType
				},
			   {
				    label: '寻单类型',
				    name: 'rfqMethod',
				    index: 'rfqMethod',
				    width: 80,
				    key: true,
				    hidden:true
			     },
				{
					width: 80,
					label: '操作',
					name: 'id',
					index: 'id',
					sortable:false,
					formatter: actFormatter
				},
				{
					label: '寻单类型',
					name: 'isLocked',
					index: 'isLocked',
					width: 80,
					key: true,
					hidden:true
				}
        ],
		sortname: 'id',
        sortorder: 'desc',
        pager: "#jqGridPager",
		rowNum: 20,//每页显示记录数
		rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
    });

	function actFormatter(cellvalue, options, rawObject) {
		var rtype = rawObject.status;
		var rmethod=rawObject.rfqMethod;
		var lock = rawObject.isLocked;
		 //debugger;
		var detailBtn ='<a class="order-del-btn btn btn-sm btn-primary js-check" data-toggle="modal" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'" data-target="#myModa1" data-action="lookLockHistory(\'' + rawObject.id + '\',\'' + rawObject.unifiedRfqNum+ '\',\'' + rawObject.ouName+ '\',\'' +"1"+ '\',\'' +rmethod+ '\')"  >查看锁定历史情况</a>';

		if(rtype=="1"&&'RAQ'==rmethod && lock =='1'){ //解锁
			detailBtn = '<a class="order-del-btn btn btn-sm btn-success js-check" data-toggle="modal" data-supplierid="'+rawObject.supplierId+'" data-target="#myModa2" data-type="'+rtype+'" data-action="lookLockHistory(\'' + rawObject.id + '\',\'' + rawObject.unifiedRfqNum+ '\',\'' + rawObject.ouName+ '\',\'' +"0"+ '\',\'' +rmethod+ '\')"  xmlns="http://www.w3.org/1999/html">解锁</a>';
		}
		if(rtype=="2"&&'RAQ'==rmethod){ //解锁
			detailBtn = '<a class="order-del-btn btn btn-sm btn-success js-check" data-toggle="modal" data-supplierid="'+rawObject.supplierId+'" data-target="#myModa2" data-type="'+rtype+'" data-action="lookLockHistory(\'' + rawObject.id + '\',\'' + rawObject.unifiedRfqNum+ '\',\'' + rawObject.ouName+ '\',\'' +"0"+ '\',\'' +rmethod+ '\')"  xmlns="http://www.w3.org/1999/html">解锁</a>';
		}
		if(rtype=="1"&&'DAC'==rmethod && lock =='1'){ //解锁
			detailBtn = '<a class="order-del-btn btn btn-sm btn-success js-check" data-toggle="modal" data-supplierid="'+rawObject.supplierId+'" data-target="#myModa2" data-type="'+rtype+'" data-action="lookLockHistory(\'' + rawObject.id + '\',\'' + rawObject.unifiedRfqNum+ '\',\'' + rawObject.ouName+ '\',\'' +"0"+ '\',\'' +rmethod+ '\')"  xmlns="http://www.w3.org/1999/html">解锁</a>';
		}
		if(rtype=="2"&&'DAC'==rmethod){ //解锁
			detailBtn = '<a class="order-del-btn btn btn-sm btn-success js-check" data-toggle="modal" data-supplierid="'+rawObject.supplierId+'" data-target="#myModa2" data-type="'+rtype+'" data-action="lookLockHistory(\'' + rawObject.id + '\',\'' + rawObject.unifiedRfqNum+ '\',\'' + rawObject.ouName+ '\',\'' +"0"+ '\',\'' +"0"+ '\')"  xmlns="http://www.w3.org/1999/html">解锁</a>';
		}
		return detailBtn;
	}

	//状态校验
	$jqGrid.on('click','.js-check', function () {
		var $this = $(this);
		var id = $this.data('supplierid');
		var type = $this.data('type');
		var action =  $this.data('action');
		RFQ.post(ctx+'/rfqQuotation/checkState',{id:id,status:type}, function (msg) {
			eval(action);
		});
	});

	var $myTab = $('#myTab');
	//搜索按钮点击
	$('button.btnSearch').on('click',function(){
		jqGridReload();
	});

	//标签页切换
	$myTab.find('[data-toggle]').on('shown.zui.tab', function(e) {
		var $activeTab = $(e.target);
		//表单重置
		var $activeContent = $($activeTab.attr('href'));
		$activeContent.find('.searchFormTab')[0].reset();
        $.placeholder();
		//状态重置
		var $lis = $activeContent.find('.navbar-nav li');
		$lis.removeClass('active');
		//默认为全部状态激活
		$lis.eq(0).addClass('active');
		//数据重新加载
		jqGridReload();
		var rfqMethod = $activeTab.data('method')||'';
		if(rfqMethod=="RAQ"||rfqMethod=='DAC'){
			$.get( ctx+'/rfqRequest/fingByRfqSupplierType',{rfqMethod:rfqMethod},function(data){
				var staticDatas = {};
				$.each(data,function(i,d){
					staticDatas[d.type] = d.count;
				});
				$lis.each(function(){
					var $a = $(this).find('a');
					$a.find('strong').text('('+(staticDatas[$a.data('type')]||0)+')');
				});
			},'json');
		}

	});

	//状态页切换
	$('div.tab-content').on('click','.navbar-nav a',function(){
		var $this = $(this);
		$this.parent().addClass('active').siblings().removeClass('active');
		jqGridReload();
	});

	function jqGridReload(){
		//选择的模式
		var $activeTab = $myTab.find('.active a');
		var rfqMethod = $activeTab.data('method')||'';
		//选择的状态以及表单
		var $activeContent = $($activeTab.attr('href'));
		var type = $activeContent.find('.navbar-nav .active a').attr('data-type')||'';
		//表单id
		var formId= $activeContent.find('.searchFormTab')[0].id;
		var params = {rfqMethod:rfqMethod,status:type};
		var postData = $.extend(form2Json(formId),params);
		$jqGrid.jqGrid('setGridParam',{postData: postData,page: 1}).trigger("reloadGrid");
	}

});
/**
 * 未开始
 */
function rfqRequestDetail(id,supplierId,rfqMethod) {
	if('RAQ'==rfqMethod){
		location.href = ctx+"/rfqRequest/rfqRequestDetail?id=" + id;
	}else if('DAC'==rfqMethod){
		window.sessionStorage.designateResult_tax="NoStart";
		location.href = ctx+"/dacReverseAuction/reverseAuctionDetail?id=" + id;
	}

}
/**
 * 查看锁定历史情况
 * 解锁
 */
function lookLockHistory(id,unifiedRfqNum,ouName,lock,rmethod){
	if("DAC" == rmethod && lock=="1" ){
		$("#unifiedRfqNum").prev().html("竞价单号 : ");
	}else if("RAQ" == rmethod && lock=="1"){
		$("#unifiedRfqNum").prev().html("询价单号 : ");
	}else if("DAC" == rmethod && lock=="0" ){
		$("#unifiedRfqNumLock").prev().html("竞价单号 : ");//竞价单号
	}else if("RAQ" == rmethod && lock=="0" ){
		$("#unifiedRfqNumLock").prev().html("询价单号 : ");//询价单号
	}
	$.ajax({
		url:ctx+"/rfqQuotationLock/lookLockHistory/"+lock,
		data:{requestId:id},
		type:'POST',
		success:function(data){
			var data = eval('('+data+')');
			if(data != null){
				if(lock=="1"){//锁定历史列表
					$("#unifiedRfqNum").html(unifiedRfqNum);//询价单号
					$("#ouName").html(ouName);//采购方
					$("#recLockUsername").html(data.recLockUsername);//锁定业务员姓名
					$("#recLockLoginName").html(data.recLockLoginName);//锁定业务员登录名
					$("#recLockTime").html(data.recLockTime);//锁定时间
					if("1" == data.isLocked){//锁定状态
						$("#isLocked").html('<span class="green">可报价</span>');
					}
					//查询锁定历史列表
					lookLockHistoryList(data.quotationNum,lock);

				}else if(lock=="0"){//解锁
					$("#rMethod").val(rmethod);
					$("#requestId").val(id);
					$("#unifiedRfqNumLock").html(unifiedRfqNum);//询价单号
					$("#ouNameLock").html(ouName);//采购方
					$("#recLockUsernameLock").html(data.recLockUsername);//锁定业务员姓名
					$("#recLockLoginNameLock").html(data.recLockLoginName);//锁定业务员登录名
					$("#recLockTimeLock").html(data.recLockTime);//锁定时间
					if("1" == data.isLocked){//锁定状态
						$("#isLockedLock").html('<span class="red">锁定</span>');
					}
					$("#recLockUseridLock").val(data.recLockUserid);
					$("#idLock").val(data.id);
					//查询解锁的锁定历史列表
					lookLockList(data.recLockUserid,data.id);
				}
			}else {
				if (lock=="1"){
					$("#unifiedRfqNum").html("");//询价单号
					$("#ouName").html("");//采购方
					$("#recLockUsername").html("");//锁定业务员姓名
					$("#recLockLoginName").html("");//锁定业务员登录名
					$("#recLockTime").html("");//锁定时间
					$("#isLocked").html("");
					//查询锁定历史列表
					lookLockHistoryList("",lock);
				}else if (lock=="0"){
					$("#requestId").val("");
					$("#unifiedRfqNumLock").html("");//询价单号
					$("#ouNameLock").html("");//采购方
					$("#recLockUsernameLock").html("");//锁定业务员姓名
					$("#recLockLoginNameLock").html("");//锁定业务员登录名
					$("#recLockTimeLock").html("");//锁定时间
					//锁定状态
					$("#isLockedLock").html("");
					//查询解锁的锁定历史列表
					lookLockList("","");
				}

			}
		}
	});
}

/**
 * 询单编号链接跳转
 */
function selectFormatter(cellvalue, options, rawObject) {
	var id = rawObject.id;
	if('RAQ'==rawObject.rfqMethod){
		return "<a class='blue' target='_blank' href='"+ctx+"/rfqRequest/rfqRequestDetail?id="+id+"' >"+cellvalue+"</a>";
	}else if('DAC'==rawObject.rfqMethod){
		return "<a class='blue' target='_blank'  href='"+ctx+"/dacReverseAuction/reverseAuctionDetail?id="+id+"' >"+cellvalue+"</a>";
	}

}

typeList=function (data){
	$("#rfqMethod").val(data);
	if('RAQ'==data||''==data){
		$("#jqGrid").jqGrid('setLabel', 3,"询价单号");
		$("#jqGrid").jqGrid('setLabel', 4,"询价标题");
		$("#jqGrid").jqGrid('setLabel', 8,"报价截止时间");
	}else if('DAC'==data){
		$("#jqGrid").jqGrid('setLabel', 3,"竞价单号");
		$("#jqGrid").jqGrid('setLabel', 4,"竞价标题");
		$("#jqGrid").jqGrid('setLabel', 8,"竞价截止时间");
	}
};

$(function(){
	$("#lookLockHistory").on('click',function(){
		var id = $("#requestId").val();
		var unifiedRfqNum = $("#unifiedRfqNumLock").html();
		var ouName = $("#ouNameLock").html();
		var rmethod = $("#rMethod").val();
		var lock = "1";
		lookLockHistory(id,unifiedRfqNum,ouName,lock,rmethod);
	})
});
/**
 * 报价锁定历史列表
 * @param quotationNum
 * @param lock
 */
function lookLockHistoryList(quotationNum,lock) {

		if(quotationNum==""){ //quotationNum为""时,清空列表
			$("#lockHistoryJqGrid").jqGrid("clearGridData");
		}

		$("#lockHistoryJqGrid").jqGrid({
			url: ctx + '/rfqQuotationLock/rfqQuotationLockHistoryList',
			postData: {quotationNum: quotationNum},
			datatype: 'json',
			mtype: 'POST',
			rownumbers:true,
			rownumWidth:50,
			colModel: [
				{
					label: 'id',
					name: 'id',
					index: 'id',
					key: true,
					hidden: true
				},
				{
					label: '报价登录账号',
					name: 'recLockLoginName',
					index: 'REC_LOCK_LOGIN_NAME',
					align: 'center'
				},
				{
					label: '员工姓名',
					name: 'recLockUsername',
					index: 'REC_LOCK_USERNAME',
					align: 'center'
				},
				{
					label: '状态',
					name: 'lockedType',
					index: 'lockedType',
					align: 'center',
					formatter: lockedTypeFormatter

				},
				{
					label: '进行解锁操作的登录账号',
					name: 'recLoginName',
					index: 'recLoginName',
					align: 'center'

				},
				{
					label: '员工姓名',
					name: 'recUsername',
					index: 'recUsername',
					align: 'center'
				},
				{
					label: '时间',
					name: 'recTime',
					index: 'recTime',
					align: 'center'

				}
			],
			jsonReader: { //映射server端返回的字段
				root: "list",//
				rows: "list",
				page: "pageNum",
				total: "pages",
				records: "total"
			},
			viewrecords: true,
			sortname: 'id',
			sortorder: 'desc',
			width: 868,
			height: "100%",
			pager: "#lockHistoryJqGridPager",
			rowNum: 20,//每页显示记录数
			rowList: [20, 30, 50, 100]//用于改变显示行数的下拉列表框的元素数组。
		});
	$("#lockHistoryJqGrid").jqGrid('setLabel', 0,"序号");
	$("#lockHistoryJqGrid").jqGrid('setGridParam', {
		postData: {quotationNum: quotationNum},
		page: 1
	}).trigger("reloadGrid");

}

function lockedTypeFormatter(cellvalue, options, rawObject){
	if ("1" == cellvalue ){
		return "可报价";
	}else if("2" == cellvalue){
		return "不可报价";
	}

}
/**
 * 更改操作员列表
 * @param quotationNum
 * @param lock
 */
function lookLockList(recLockUserid,lockId) {

	if(recLockUserid==""){
		$("#lockJqGrid").jqGrid("clearGridData");
	}
	$("#lockJqGrid").jqGrid({
			datatype: 'local',
			rownumbers:true,
			rownumWidth:50,
			colModel: [
				{
					label: 'id',
					name: 'userLoginNo',
					index: 'userLoginNo',
					key: true,
					hidden: true
				},
				{
					label: '登录账号',
					name: 'userLoginNo',
					index: 'userLoginNo',
					align: 'center'
				},
				{
					label: '员工姓名',
					name: 'userName',
					index: 'userName',
					align: 'center'
				},
				{
					label: '操作',
					name: 'postName',
					index: 'postName',
					align: 'center',
					formatter: lockChangeFormatter
				}
			],
			viewrecords: true,
			//sortname: 'userLoginNo',
			//sortorder: 'asc',
			width: 868,
			height: "100%",
			 pager: "#lockJqGridPager",
			rowNum: 20,//每页显示记录数
			rowList: [20, 30, 50, 100]//用于改变显示行数的下拉列表框的元素数组。
		});
	$.post(ctx + '/rfqQuotationLock/getLockUserList',{}, function (data) {
		$("#lockJqGrid").jqGrid('setGridParam',{datatype:'local',data:data.list}).trigger('reloadGrid');
	},'json');

	$("#lockJqGrid").jqGrid('setLabel', 0,"序号");


}


	/**
	 * 更换操作员格式化
	 */
	function lockChangeFormatter(cellvalue, options, rawObject) {
		var lockId = $("#idLock").val();//报价锁id
		var recLockUserid = $("#recLockUseridLock").val();//报价锁报价人id
		var recLockUsername = rawObject.userName;//用户名字
		var userLoginNo = rawObject.userLoginNo;//用户id
		var detailBtn = '<a class="order-del-btn btn btn-sm btn-primary" onclick="changeOperator(\'' + lockId + '\',\'' + recLockUsername + '\',\'' + userLoginNo + '\',\'' + userLoginNo + '\')">更换操作员</a>';
		if (recLockUserid != userLoginNo){
			return detailBtn;
		}else if (recLockUserid == userLoginNo){
			return '';
		}
	}
function changeOperator(lockId,recLockUsername,recLockLoginName,recLockUserid){
	$.ajax({
		url:ctx+"/rfqQuotationLock/editRfqQuotationLockUser",
		data:{
			quotationLockId:lockId,
			recLockUsername:recLockUsername,
			recLockLoginName:recLockLoginName,
			recLockUserid:recLockUserid
		},
		type:'POST',
		success:function(data){
			var data = eval('('+data+')');
			if (data!=null){
				$.zui.messager.show(data.msg, {placement: 'center', type: 'success', icon: 'icon-ok-sign'});
				lookLockHistory(data.id,data.unifiedRfqNum,data.ouName,"0",data.rfqMethod);
			}
		}
	});
}